package com.samsung.controller.vote;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.samsung.common.util.BaseUtil;
import com.samsung.common.util.Constant;
import com.samsung.model.user.User;
import com.samsung.model.vote.VoteRecord;
import com.samsung.model.vote.VoteTopic;
import com.samsung.service.vote.TopicService;
import com.samsung.service.vote.VoteHistoryService;

/**
 * 
 * @ClassName: VoteHistoryController
 * @Description: TODO(将投票结果保存到数据库)
 * @author qin1.li
 * @date 2015年4月27日下午2:05:31
 * @sine 1.0
 */
@Controller
@RequestMapping("/vote")
public class VoteHistoryController extends MultiActionController {
	@Autowired
	private VoteHistoryService voteHistoryService;
	@Autowired
	private TopicService topicService;

	/**
	 * @Title: saveCheckVoteHistory
	 * @Description: TODO(保存投票结果)
	 * @param @param request
	 * @param @param response
	 * @param @return 设定文件
	 * @return Map<String,Object> 返回类型
	 * @throws
	 */
	@ResponseBody
	@RequestMapping("/saveCheckVoteHistory")
	public Map<String, Object> saveCheckVoteHistory(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String topicId = request.getParameter("topicId");
		String type = request.getParameter("type");
		String oids = request.getParameter("oids");
		String ip = BaseUtil.getRemoteHost(request);
		User user = BaseUtil.getLoginedUser(request);
		String uid = "";
		if (user != null) {
			uid = user.getUid();
		}

		// 校验逻辑
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// --------------------------------------------------------------
		if (BaseUtil.isEmpty(topicId)) {
			resultMap.put("success", false);
			resultMap.put("msg", "投票主题编号不能为空！");
			return resultMap;
		}

		VoteTopic topic = topicService.getTopic(topicId);
		if (topic == null) {
			resultMap.put("success", false);
			resultMap.put("msg", "该投票主题不存在或已被删除！");
			return resultMap;
		}
		
		if (BaseUtil.isEmpty(oids)) {
			resultMap.put("success", false);
			resultMap.put("msg", "请至少选择一个投票项！");
			return resultMap;
		}

		if (ip == null) {
			resultMap.put("success", false);
			resultMap.put("msg", "您的IP无法获取！");
			return resultMap;
		}

		if (new Date().before(topic.getDeadline())) {
			// 当前主题截止时间仍然可投票
			Object userObj = request.getSession().getAttribute(Constant.LOGIN_TOKEN);
			if (userObj == null) {
				// 游客
				if (topic.getScope() == 0) {
					// 所有人可投
					int cnt = voteHistoryService.getCountByUserAndIP(topicId, "", ip);
					// 是否投过
					if (cnt > 0) {
						resultMap.put("success", false);
						resultMap.put("msg", "您已投过该主题，不能重复投票！");
						resultMap.put("url", request.getContextPath()+ "/vote/statisticsPage.do?topicId=" + topicId + "&r=" + Math.random());
						return resultMap;
					}
				} else {
					// 游客不可投隐私主题
					resultMap.put("success", false);
					resultMap.put("msg", "该主题为隐私主题，请先登录后投票！");
					resultMap.put("url", request.getContextPath()+"/user/loginPage.do");
					return resultMap;
				}
			} else {
				// 会员
				// 是否投过
				User u = (User) userObj;
				int cnt = voteHistoryService.getCountByUserAndIP(topicId, u.getUid(), ip);
				// 是否投过
				if (cnt > 0) {
					// 会员已投过该主题
					resultMap.put("success", false);
					resultMap.put("msg", "您已投过该主题，不能重复投票！");
					resultMap.put("url", request.getContextPath()+ "/vote/statisticsPage.do?topicId=" + topicId + "&r=" + Math.random());
					return resultMap;
				}
			}
		} else {
			// 当前主题已过期，不能投票
			// 跳转至统计页面
			resultMap.put("success", false);
			resultMap.put("msg", "该投票主题已过期！");
			resultMap.put("url", request.getContextPath()+ "/vote/statisticsPage.do?topicId=" + topicId + "&r=" + Math.random());
			return resultMap;
		}
		// --------------------------------------------------------------

		if ("0".equals(type)) {
			VoteRecord vh = new VoteRecord();
			vh.setHid(BaseUtil.getUUID());
			vh.setIp(ip);
			vh.setOid(oids);
			vh.setTid(topicId);
			vh.setUid(uid);
			vh.setVoteTime(new Date());
			int cnt = voteHistoryService.saveVoteHistory(vh);
			if (cnt > 0) {
				resultMap.put("success", true);
				resultMap.put("msg", "投票成功！");
			} else {
				resultMap.put("success", false);
				resultMap.put("msg", "投票失败！");
			}
		}
		/**
		 * 多选保存
		 */
		else {
			String[] oidArr = oids.split(",");
			for (int i = 0; i < oidArr.length; i++) {
				VoteRecord vh = new VoteRecord();
				vh.setHid(BaseUtil.getUUID());
				vh.setIp(ip);
				vh.setOid(oidArr[i]);
				vh.setTid(topicId);
				vh.setUid(uid);
				vh.setVoteTime(new Date());
				voteHistoryService.saveVoteHistory(vh);
			}

			resultMap.put("success", true);
			resultMap.put("msg", "投票成功！");
		}

		return resultMap;
	}

}